<template>
  <div class="app-container"> 
    <!-- 标题栏 -->
    <div class="header-bar">
      <div class="header-bar-left">
        <el-button type="primary" class="mb-4" @click="handleAddCustomer">添加客户</el-button>
        <el-button class="mb-4 ml-2" @click="handleImport">导入</el-button>
      </div>
      <el-input
        placeholder="请输入公司名称/主营业务"
        style="width: 250px; float: right; margin-bottom: 10px;"
        v-model="queryParams.keyword"
        @keyup.enter="handleSearch"
        clearable
      >
        <template #append>
          <el-button icon="Search" @click="handleSearch"></el-button>
        </template>
      </el-input>
    </div>
    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="customerList" style="width: 100%" border>
      <el-table-column prop="socialCreditCode" label="统一社会信用代码" align="left" :show-overflow-tooltip="true">
        <template #header>
          <div class="header-search-container">
            <span>统一社会信用代码</span>
            <el-popover placement="bottom" width="250" trigger="click">
              <template #reference>
                <el-icon class="search-icon"><Search /></el-icon>
              </template>
              <el-input 
                v-model="queryParams.socialCreditCode" 
                placeholder="请输入统一社会信用代码" 
                clearable
                width="200"
                @keyup.enter="handleSearch"
              />
              <div style="text-align: right; margin-top: 10px;">
                <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
                <el-button size="small" @click="clearSearch('socialCreditCode')">重置</el-button>
              </div>
            </el-popover>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="companyName" label="公司名称" align="left" :show-overflow-tooltip="true" />
      <el-table-column prop="mainBusiness" label="主营业务" align="left" :show-overflow-tooltip="true" />
      <el-table-column prop="money" label="合同金额" align="left" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ scope.row.money }}万元</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最近业务往来时间" align="left" :show-overflow-tooltip="true">
        <!-- <template #header>
          <div class="header-search-container">
            <span>最近业务往来时间</span>
            <el-popover placement="bottom" width="300" trigger="click">
              <template #reference>
                <el-icon class="search-icon"><Calendar /></el-icon>
              </template>
              <el-date-picker
                v-model="[queryParams.startTime, queryParams.endTime]"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
              <div style="text-align: right; margin-top: 10px;">
                <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
                <el-button size="small" @click="clearDateSearch">重置</el-button>
              </div>
            </el-popover>
          </div>
        </template> -->
      </el-table-column>
      <el-table-column label="操作" align="left">
        <template #default="scope">
          <el-link type="primary" @click="handleViewDetail(scope.row)">查看详情</el-link>
          <el-link type="primary" class="ml5" @click="handleEdit(scope.row)">编辑</el-link>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <el-pagination
      style="margin-top: 20px; justify-content: flex-end;"
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 客户编辑/添加弹窗组件 -->
    <update-customer
      :visible="updateCustomerVisible"
      :is-edit="isEditMode"
      :edit-data="selectedCustomer"
      :region-data="chinaRegion"
      :tabs-list="tabsList"
      @confirm="handleCustomerConfirm"
      @close="handleCustomerClose"
      @update:visible="updateCustomerVisible = $event"
    />
    
    <!-- 客户查看详情组件 -->
    <customer-info
      :visible="customerInfoVisible"
      :customer-data="selectedCustomer"
      :tabs-list="infoTabsList"
      @close="handleCustomerInfoClose"
      @update:visible="customerInfoVisible = $event"
    />
    
    <!-- 客户数据导入对话框 -->
    <el-dialog title="导入" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :auto-upload="false"
        :before-upload="handleBeforeUpload"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-remove="handleRemove"
        :on-change="handleImportFileChange"
        :file-list="fileList"
        drag
      >
        <el-button type="primary">选择文件</el-button>
        <template #tip>
          <div class="el-upload__tip">
            <span>仅允许导入xls、xlsx格式文件，最多支持10个文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline; margin-left: 10px"
              @click="exportTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading">
            {{ upload.isUploading ? '上传中...' : '确 定' }}
          </el-button>
          <el-button @click="cancelFileForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CustomerManagement">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
// 导入省市区数据
import chinaRegion from '@/utils/chinaRegion.json'
// 导入客户编辑/添加组件
import updateCustomer from './updateCustomer.vue'
// 导入客户查看详情组件
import customerInfo from './customerInfo.vue'
import {
  getCustomerContractInfo,
  addCustomerInfo,
  updateCustomerInfo,
  getCustomerInfo,
  downLoadTemplate,
  importCustomerInfo
} from '@/api/business/customer'
import { getToken } from '@/utils/auth'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  socialCreditCode: '',
  startTime: '',
  endTime: ''
})

// 数据总数
const total = ref(0) // 模拟数据总数
const customerList = ref([])
// 加载状态
const loading = ref(false)

// 弹窗相关状态
const updateCustomerVisible = ref(false)
const customerInfoVisible = ref(false)
const isEditMode = ref(false)
const selectedCustomer = ref({})
// Excel导入参数
const upload = reactive({
  // 是否显示弹出层（Excel导入）
  open: false,
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/business/customer/importData'
})

// 文件列表引用
const fileList = ref([])
const importFile = ref(null)
// el-upload组件引用
const uploadRef = ref(null)

// 编辑/添加页面的标签列表数据
const tabsList = ref([
  { name: 'basic', label: '基本信息' },
  { name: 'financial', label: '财务信息' },
])

// 查看详情页面的标签列表数据
const infoTabsList = ref([
  { name: 'basic', label: '基本信息' },
  { name: 'financial', label: '财务信息' },
  { name: 'businessInfo', label: '业务往来信息' },
  { name: 'changeInfo', label: '信息变更' }
])

// 获取客户列表
function getCustomerList () {
  loading.value = true
  getCustomerContractInfo(queryParams).then(res => {
    if (res.code === 200) {
      loading.value = false;
      customerList.value = res.data?.list || [];
      total.value = res.data?.total || 0;
    }
  }).catch(() => {
    loading.value = false;
    customerList.value = [];
    total.value = 0;
  });
}
// 分页大小改变
function handleSizeChange(val) {
  queryParams.pageSize = val
  queryParams.pageNum = 1
  getCustomerList()
}

// 当前页码改变
function handleCurrentChange(val) {
  queryParams.pageNum = val
  getCustomerList()
}
// 搜索
function handleSearch() {
  queryParams.pageNum = 1
  getCustomerList()
}

// 清空统一社会信用代码搜索
function clearSearch(field) {
  queryParams[field] = ''
  getCustomerList()
}

// 添加客户
function handleAddCustomer() {
  isEditMode.value = false
  selectedCustomer.value = {}
  updateCustomerVisible.value = true
}

// 导入
function handleImport() {
  upload.open = true
}
// 下载模板操作
function exportTemplate() {
  downLoadTemplate({}).then((response) => {
    const fileUrl = response?.data
    if (fileUrl) {
      const fileName = '客户信息导入模板.xlsx' // 中文需要转码 (前端乱码为百分号形式）
      saveAs(fileUrl, fileName)
    }
  })
}

// 处理文件上传中
function handleFileUploadProgress(event, file, fileList) {
  upload.isUploading = true
}

// 处理文件上传成功
function handleFileSuccess(response, file, fileList) {
  console.log('文件上传成功:', file.name, response)
}
function handleImportFileChange(uploadFile, uploadFiles) {
  // console.log('导入文件改变:', file.name, fileList)
  importFile.value = uploadFile.raw
  fileList.value = uploadFiles
}
// 处理文件移除
function handleRemove(file) {
  // 更新本地文件列表
  const index = fileList.value.findIndex(item => item.uid === file.uid)
  if (index > -1) {
    fileList.value.splice(index, 1)
  }
}

// 处理文件选择前的校验
function handleBeforeUpload(file) {
  // 检查文件类型
  const isValidType = file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
  if (!isValidType) {
    ElMessage.warning('仅支持.xlsx和.xls格式文件')
    return false
  }
  
  // 检查文件大小（可选）
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.warning('文件大小不能超过2MB')
    return false
  }
  
  return true
}

// 取消上传文件
function cancelFileForm() {
  // 重置上传状态
  upload.isUploading = false
  // 清空文件列表
  fileList.value = []
  importFile.value = null
  // 关闭弹窗
  upload.open = false
}

// 提交上传文件（使用el-upload组件的手动上传）
async function submitFileForm() {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }
  upload.isUploading = true
  try {
    const formData = new FormData()
    formData.append('file', importFile.value)
    // 调用导入客户信息接口
    importCustomerInfo(formData).then(res => {
      if (res.code === 200) {
        ElMessage.success(res.data)
        // 刷新客户列表
        getCustomerList()
        // 关闭弹窗
        upload.open = false
        // 清空文件列表
        fileList.value = []
        importFile.value = null
      }
    }).catch(() => {
      ElMessage.error('上传过程中出现错误')
    })
  } catch (error) {
    ElMessage.error('上传过程中出现错误')
  } finally {
    upload.isUploading = false
  }
}

// 查看详情
function handleViewDetail(row) {
  // 调用查看详情接口
  getCustomerInfo(row.id).then(res => {
    if (res.code === 200) {
      // 合并返回的详情数据
      selectedCustomer.value = { ...res.data }
    }
  }).catch(() => {
    ElMessage.error('获取详情失败')
    selectedCustomer.value = {}
  })
  // 打开详情弹窗
  customerInfoVisible.value = true
}

// 编辑客户
function handleEdit(row) {
  isEditMode.value = true
  // 深拷贝选中的客户数据
  selectedCustomer.value = JSON.parse(JSON.stringify(row))
  updateCustomerVisible.value = true
}

// 处理客户信息确认
function handleCustomerConfirm(formData) {
  const obj = {
    basicInfo: {
      "socialCreditCode": formData.socialCreditCode,
      "companyName": formData.companyName,
      "registeredCapital": formData.registeredCapital,
      "registeredAddress": formData.registeredAddress,
      "mainBusiness": formData.mainBusiness,
      "defaultDeliveryAddress": formData.defaultDeliveryAddress,
      "contactPerson": formData.contactPerson,
      "contactInformation": formData.contactInformation
    },
    financialInfo: {
      "taxpayerType": formData.taxpayerType,
      "invoiceType": formData.invoiceType,
      "invoicingBank": formData.invoicingBank,
      "invoicingBankNumber": formData.invoicingBankNumber,
      "invoicingAddress": formData.invoiceAddress
    }
  }
  if (isEditMode.value) {
    const newObj = { ...obj, id: selectedCustomer.value.id }
    updateCustomerInfo(newObj).then(res => {
      if (res.code === 200) {
        ElMessage.success('编辑成功')
        getCustomerList()
        updateCustomerVisible.value = false
      }
    }).catch(() => {
      ElMessage.error('添加失败')
    })
  } else {
    addCustomerInfo(obj).then(res => {
      if (res.code === 200) {
        ElMessage.success('添加成功')
        getCustomerList()
        updateCustomerVisible.value = false
      }
    }).catch(() => {
      ElMessage.error('添加失败')
    })
  }
}

// 处理客户编辑弹窗关闭
function handleCustomerClose() {
  updateCustomerVisible.value = false
  // 重置相关状态
  selectedCustomer.value = {}
}

// 处理客户详情弹窗关闭
function handleCustomerInfoClose() {
  customerInfoVisible.value = false
  // 重置相关状态
  selectedCustomer.value = {}
}

// 初始化
onMounted(() => {
  getCustomerList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  box-sizing: border-box;
}

.ml5 {
  margin-left: 5px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
  /* padding: 0 10px; */
  box-sizing: border-box;
  width: 100%;
}

:deep(.el-pagination) {
  display: flex;
  justify-content: flex-end;
  flex-wrap: wrap;
}

.header-search-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-icon {
  margin-left: 100px;
  cursor: pointer;
  color: #409eff;
  font-size: 16px;
}

.search-icon:hover {
  color: #66b1ff;
}
</style>

<style>
/* 可以保留一些样式，为el-upload提供更好的显示效果 */
:deep(.el-upload-list__item) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>